<template>
  <!-- 流程实例相关信息 -->
  <BasicForm @register="registerForm" />
  <!-- 状态颜色标识判断 -->
  <div class="status-container">
    <span><span class="status not-started"></span>未开始</span>
    <span><span class="status in-progress"></span>进行中</span>
    <span><span class="status completed"></span>已完成</span>
  </div>
  <!-- 流程图 -->
  <Row style="width: 100%; height: 250px">
    <Col :span="24" :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
      <div ref="graphContainer" style="width: 100%; height: 600px"></div>
    </Col>
  </Row>
  <!-- 流程表格 -->
  <Card>
    <Row :gutter="12">
      <Col :span="6" :xs="6" :sm="6" :md="6" :lg="6" :xl="6">
        <BasicTree
          :toolbar="false"
          :search="true"
          :treeData="fileList"
          :replaceFields="{ key: 'oid', title: 'filename' }"
          @select="setSelectedKeys"
        />
      </Col>
      <Col :span="18" :xs="18" :sm="18" :md="18" :lg="18" :xl="18">
        <BasicTable
          @register="registerTable"
          :data-source="flowExampleList"
          :searchInfo="searchInfo"
        >
          <!-- 创建时间 -->
          <template #stepsigntime="{ text: stepsigntime }">
            <span>
              {{ proxy.$filters.filterTime(stepsigntime) }}
            </span>
          </template>
        </BasicTable>
      </Col>
    </Row>
  </Card>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch, getCurrentInstance, nextTick } from 'vue';
  import { Graph } from '@antv/x6';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicTree } from '/@/components/Tree/index';
  import { BasicTable, useTable } from '/@/components/Table';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Row, Col, Card } from 'ant-design-vue';
  import { getBorrowForm, getFlowDetailColumns } from '/@/views/demo/documentManager/tableData';
  import { getBorrowFlowInstance } from '/@/api/demo/document';

  const { t } = useI18n();
  const { proxy }: any = getCurrentInstance();
  const fileList = ref<any>([]);
  const searchInfo = ref<any>({
    oid: '',
    version: null,
  });
  const flowExampleList = ref<any>([]);
  // 流程图数据
  const stepsList = ref<Step[]>([]);

  // 初始化详情表单
  const [registerForm, { setFieldsValue }] = useForm({
    schemas: getBorrowForm(),
    labelWidth: 110,
    colon: true,
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
    showResetButton: false,
    showSubmitButton: false,
    showAdvancedButton: true,
  });

  // 初始化表格
  const [registerTable] = useTable({
    columns: getFlowDetailColumns(),
    fetchSetting: {
      // 当前页传递给后台的字段名称
      pageField: 'CurrentPage',
      // 后台每页显示的数量字段名称
      sizeField: 'PageSizes',
      // 接口返回的表单数据字段名称
      listField: 'steplist',
      // 接口返回的表格总数字段名称
      totalField: 'count',
    },
    showIndexColumn: false,
    showTableSetting: false, // 表格设置工具配置
    bordered: true,
    canResize: false,
  });

  // 选择关联对象
  const setSelectedKeys = (keys) => {
    searchInfo.value.oid = keys[0];
    getData();
  };

  interface Step {
    id: string;
    label: string;
    status: '完成' | '就绪' | '未完成';
    next: string[];
  }

  const props = defineProps({
    currentRecord: {
      type: Object,
      default: () => ({}),
    },
  });

  const graphContainer = ref<HTMLDivElement | null>(null);

  const renderGraph = () => {
    if (!graphContainer.value) return;

    // 记录节点信息
    const nodeMap: Record<string, any> = {};
    const levelMap: Record<string, number> = {};
    const spaceX = 200;
    const spaceY = 130;

    const dfs = (nodeId: string, level: number) => {
      if (levelMap[nodeId] != null && levelMap[nodeId] >= level) return;
      levelMap[nodeId] = level;
      const node = stepsList.value.find((s) => s.id === nodeId);
      if (node) {
        node.next.forEach((n) => dfs(n, level + 1));
      }
    };

    if (stepsList.value.length === 0) return;
    dfs(stepsList.value[0].id, 0);

    const layers: Record<number, Step[]> = {};
    stepsList.value.forEach((s) => {
      const level = levelMap[s.id] ?? 0;
      if (!layers[level]) layers[level] = [];
      layers[level].push(s);
    });

    const layerCount = Object.keys(layers).length;
    const maxNodesInLayer = Math.max(...Object.values(layers).map((n) => n.length));
    const canvasWidth = Math.max(layerCount * spaceX + 200, 1000);
    const canvasHeight = Math.max(maxNodesInLayer * spaceY + 200, 400);

    const graph = new Graph({
      container: graphContainer.value,
      width: canvasWidth,
      height: canvasHeight,
      grid: true,
      interacting: {
        nodeMovable: false,
        edgeMovable: false,
      },
      panning: {
        enabled: true,
      },
      mousewheel: {
        enabled: true,
      },
    });

    Object.entries(layers).forEach(([levelStr, nodes]) => {
      const level = parseInt(levelStr);
      nodes.forEach((node, i) => {
        const x = level * spaceX + 30;
        const y = i * spaceY + 30;
        const color =
          node.status === '完成' ? '#00cc00' : node.status === '就绪' ? '#2486b9' : '#999';

        const x6Node = graph.addNode({
          id: node.id,
          x,
          y,
          width: 100,
          height: 30,
          label: node.label,
          shape: 'rect',
          attrs: {
            body: {
              fill: color,
              stroke: '#555',
              rx: 8,
              ry: 8,
            },
            label: {
              fill: '#fff',
              fontSize: 12,
              fontWeight: 'bold',
            },
          },
        });

        nodeMap[node.id] = x6Node;
      });
    });

    stepsList.value.forEach((s) => {
      s.next.forEach((targetId) => {
        graph.addEdge({
          source: s.id,
          target: targetId,
          attrs: {
            line: {
              stroke: '#AAB7C4',
              strokeWidth: 2,
              targetMarker: {
                name: 'classic',
                size: 6,
              },
            },
          },
        });
      });
    });
  };
  const getData = () => {
    const params = {
      oId: props.currentRecord.id,
      version: props.currentRecord.version,
    };
    searchInfo.value.oid = props.currentRecord.id;
    searchInfo.value.version = props.currentRecord.version;
    getBorrowFlowInstance(params).then((res) => {
      fileList.value = res.filelist;
      flowExampleList.value = res.steplist;
      // 延迟设置 stepsList，避免竞争
      nextTick(() => {
        setFieldsValue(res);
        stepsList.value = res.drawStep == null ? [] : res.drawStep;
      });
    });
  };

  // 初次加载
  onMounted(() => {
    setTimeout(() => {
      getData();
      renderGraph();
    }, 50);
  });

  // 监听 stepsList.value 变化自动重绘
  watch(
    () => stepsList.value,
    () => {
      // 清空旧图
      if (graphContainer.value) {
        graphContainer.value.innerHTML = '';
      }
      renderGraph();
    },
    { deep: true },
  );
</script>

<style lang="less" scoped>
  ::v-deep(.ant-calendar-picker) {
    width: 100% !important;
  }

  .status-container {
    display: flex;
    align-items: center;
  }

  /* 通用样式，设置状态标识的基本样式 */
  .status {
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 5px;
  }

  /* 未开始状态的样式 */
  .status.not-started {
    background-color: #ccc;
  }

  /* 进行中状态的样式 */
  .status.in-progress {
    background-color: #007bff;
  }

  /* 已完成状态的样式 */
  .status.completed {
    background-color: #28a745;
  }

  /* 给每个状态标识和文字的组合添加右边距 */
  .status-container span {
    margin-right: 15px;
  }
</style>
